package com.jty.module_login.viewmodel

import android.text.TextUtils
import android.view.View
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.jty.lib_base.base.BaseBean
import com.jty.lib_base.base.BaseViewModel
import com.jty.lib_base.base.MyApplication
import com.jty.lib_base.binding.command.BindingAction
import com.jty.lib_base.binding.command.BindingCommand
import com.jty.lib_base.binding.command.BindingConsumer
import com.jty.lib_base.bus.event.SingleLiveEvent
import com.jty.lib_base.data.DataRepository
import com.jty.lib_base.event.LiveBusCenter
import com.jty.lib_base.extension.ApiSubscriptHelper
import com.jty.lib_base.utils.ComUtils
import com.jty.lib_base.utils.RxThreadHelper
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import okhttp3.RequestBody
import java.util.concurrent.TimeUnit


/**
 * author: zhouyh
 * created on: 2021/9/17 11:36 下午
 * description: 找回密码viewModel
 * 绑定application和数据源
 */
class RePasswordViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    var account: ObservableField<String> = ObservableField("")
    var code: ObservableField<String> = ObservableField("")
    var codeTimer: ObservableField<String> = ObservableField("发送验证码")
    var password: ObservableField<String> = ObservableField("")
    var repassword: ObservableField<String> = ObservableField("")

    var eyePasswordState: ObservableBoolean = ObservableBoolean(false)
    var eyeRePasswordState: ObservableBoolean = ObservableBoolean(false)

    val uc = UIChangeEvent()

    class UIChangeEvent {
        val passwordVisibleEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
        val rePasswordVisibleEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
        val sendCodeClickEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
    }

    val onAccountChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer {
        account.set(it)
    })

    val onCodeChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer {
        code.set(it)
    })

    val onPasswordChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer {
        password.set(it)
    })

    val onRePasswordChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer {
        repassword.set(it)
    })

    val onClearClickCommand: View.OnClickListener = View.OnClickListener {
        account.set("")
    }

    val onPwdEyeClickCommand: BindingCommand<Boolean> = BindingCommand(BindingAction {
        if (eyePasswordState.get()) {
            eyePasswordState.set(false)
        } else {
            eyePasswordState.set(true)
        }
        uc.passwordVisibleEvent.postValue(eyePasswordState.get())
    })

    val onRePwdEyeClickCommand: BindingCommand<Boolean> = BindingCommand(BindingAction {
        if (eyeRePasswordState.get()) {
            eyeRePasswordState.set(false)
        } else {
            eyeRePasswordState.set(true)
        }
        uc.rePasswordVisibleEvent.postValue(eyeRePasswordState.get())
    })

    private var count = 60
    private var subscribe: Disposable? = null

    /**
     * 开始倒计时
     */
    private fun startTimer() {
        subscribe = Observable
            .interval(0, 1, TimeUnit.SECONDS)
            .map {
                count--
            }
            .subscribeOn(Schedulers.io())
            .doOnSubscribe {
                uc.sendCodeClickEvent.postValue(false)
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (count == 0) {
                    count = 60
                    codeTimer.set("发送验证码")
                    removeSubscribe()
                    uc.sendCodeClickEvent.postValue(true)
                } else codeTimer.set("重新发送${count}s")
            }
    }

    private fun removeSubscribe() {
        subscribe?.let { removeSubscribe(it) }
    }

    private fun addSubscribe(){
        subscribe?.let { addSubscribe(it) }
    }


    //发送验证码
    val onGetCodeClickCommand: View.OnClickListener = View.OnClickListener {
        if (TextUtils.isEmpty(account.get())) {
            showNormalToast("请输入手机号")
            return@OnClickListener
        }

        val json = ComUtils.getHashmapByStr(
            arrayOf("mobile","type"),
            arrayOf(account.get().toString(),10)
        )
        var requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
            GsonUtils.toJson(json))

        model.getCode(requestBody)
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriptHelper<BaseBean<String>>() {
                override fun onResult(t: BaseBean<String>) {
                    if (t.code == 0) {
                        startTimer()
                        addSubscribe()
                    }
                }
                override fun onFailed(msg: String?) {
                    showNormalToast(msg)
                }
            })

    }
    val onFindPwdClickCommand: BindingCommand<Any> = BindingCommand(BindingAction {
        if(password.get()!!.length < 6 || password.get()!!.length > 12 || password.get()!!.contains(" ")) {
            showNormalToast("请输入6-12位英文+数字组合")
            return@BindingAction
        }

        if (password.get() != repassword.get()) {
            showNormalToast("两次密码输入不一致")
            return@BindingAction
        }

        var json = ComUtils.getHashmapByStr(
            arrayOf("mobile","verCode","newPassword"),
            arrayOf(account.get().toString(), code.get().toString(), password.get().toString())
        )
        val requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
            GsonUtils.toJson(json))
        model.rePassword(requestBody)
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriptHelper<BaseBean<*>>() {
                override fun onResult(t: BaseBean<*>) {
                    dismissLoading()
                    if (t.code == 0) {
                        model.saveLoginState(false)
                        LiveBusCenter.postRegisterSuccessEvent(account.get(), password.get())
                        finish()
                    }
                }
                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showNormalToast(msg)
                }
            })
    })

}
